﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using DevExpress.UserSkins;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using System.Threading;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using XChip_Common;
using System.Reflection;


namespace XChipTool
{
    static class Program
    {

        [DllImport("ver6.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr load_para_hdr(string pFileName, int[] gamma_y_list);
        [DllImport("ver6.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void para_gamma_calc(int[] x_list, int[] y_list, int[] gamma_gain, int[] gamma_slope);
        [DllImport("ver6.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr para_decmp_calc(int[] node_cmp, int[] offset_cmp, int[] ratio_cmp, int[] node_dec, int[] offset_dec, int[] ratio_dec, int curve_number);

        [DllImport("ver6.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void gamma_validation(int[] x_list, int[] gain_list, int[] slope_list, char[] path);
        [DllImport("ver6.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void gamma_restore(int[] x_list, int[] x_list_restore, int[] y_list_restore, int[] gain_list, int[] slope_list);

        [DllImport("ver6.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void compression_validation(int[] node, int[] offset, int[] ratio, int curve_number, char[] path);
        [DllImport("ver6.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void decompression_validation(int[] node, int[] offset, int[] ratio, int curve_number, char[] path);

        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            //AdbProcessManager.KillAllAdbProcesses();
            //设置应用程序处理异常方式：ThreadException处理
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            //处理UI线程异常
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            //处理非UI线程异常
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //var services = new ServiceCollection();
            // ContainerBuilder builder = new ContainerBuilder();
            BonusSkins.Register();
            SkinManager.EnableFormSkins();
            //The Asphalt World
            UserLookAndFeel.Default.SetSkinStyle("Seven Classic");  // 设置皮肤样式
                                                                    //Application.Run(new XChipForm());
                                                                    //XChipForm.ActiveForm.BackColor = Color.Red;

            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            //创建上一级目录快捷图标
            if (ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["IsSerial"].Value == "USB" && ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["IsI2C"].Value != "1")
            {

                if (!ShortCutHelper.DoesShortcutExist($"{Path.Combine(new DirectoryInfo(Application.StartupPath).Parent.FullName, string.Format("{0}.lnk", "XChipTool_Usb_ISP3.0"))}"))
                {
                    ShortCutHelper.Createashortcutontheparentpath("XChipTool_Usb_ISP3.0", Application.ExecutablePath, "USB");
                }

                if (!ShortCutHelper.DoesShortcutExist($"{Path.Combine(desktopPath, string.Format("{0}.lnk", "XChipTool_Usb_ISP3.0"))}"))
                {
                    ShortCutHelper.CreateShortcutOnDesktop("XChipTool_Usb_ISP3.0", Application.ExecutablePath, "USB");
                }
                else
                {
                    //获取桌面图标完整路径
                    string shortcutPath = Path.Combine(desktopPath, "XChipTool_Usb_ISP3.0.lnk");
                    //判断桌面图标快捷方式的目标路径
                    string targetPath = ShortCutHelper.GetShortcutTargetPath(shortcutPath);
                    //判断桌面图标快捷方式的目标路径文件是否存在
                    if (!File.Exists(targetPath))
                    {
                        // 删除快捷方式文件
                        File.Delete(shortcutPath);
                        ShortCutHelper.CreateShortcutOnDesktop("XChipTool_Usb_ISP3.0", Application.ExecutablePath, "USB");
                    }
                }
                if (ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["1ico"].Value == "0")
                {
                    //获取桌面图标完整路径
                    string shortcutPath = Path.Combine(desktopPath, "XChipTool_Usb_ISP3.0.lnk");
                    //判断桌面图标快捷方式的目标路径
                    string targetPath = ShortCutHelper.GetShortcutTargetPath(shortcutPath);
                    //判断桌面图标快捷方式的目标路径文件是否存在
                    if (File.Exists(shortcutPath))
                    {
                        // 删除快捷方式文件
                        File.Delete(shortcutPath);
                        ShortCutHelper.CreateShortcutOnDesktop("XChipTool_Usb_ISP3.0", Application.ExecutablePath, "USB");
                        AppHelper.UpdateAppConfig("1ico", "1");
                    }
                }

            }
            else if (ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["IsSerial"].Value == "USB" && ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["IsI2C"].Value == "1")
            {
                if (!ShortCutHelper.DoesShortcutExist($"{Path.Combine(new DirectoryInfo(Application.StartupPath).Parent.FullName, string.Format("{0}.lnk", "XChipTool_I2C_ISP3.0"))}"))
                {
                    ShortCutHelper.Createashortcutontheparentpath("XChipTool_I2C_ISP3.0", Application.ExecutablePath, "I2C");
                }

                if (!ShortCutHelper.DoesShortcutExist($"{Path.Combine(desktopPath, string.Format("{0}.lnk", "XChipTool_I2C_ISP3.0"))}"))
                {
                    ShortCutHelper.CreateShortcutOnDesktop("XChipTool_I2C_ISP3.0", Application.ExecutablePath, "I2C");
                }
                else
                {
                    //获取桌面图标完整路径
                    string shortcutPath = Path.Combine(desktopPath, "XChipTool_I2C_ISP3.0.lnk");
                    //判断桌面图标快捷方式的目标路径
                    string targetPath = ShortCutHelper.GetShortcutTargetPath(shortcutPath);
                    //判断桌面图标快捷方式的目标路径文件是否存在
                    if (!File.Exists(targetPath))
                    {
                        // 删除快捷方式文件
                        File.Delete(shortcutPath);
                        ShortCutHelper.CreateShortcutOnDesktop("XChipTool_I2C_ISP3.0", Application.ExecutablePath, "I2C");
                    }
                }

            }
            else
            {
                if (ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["ismipiout"].Value == "1")
                {
                    if (!ShortCutHelper.DoesShortcutExist($"{Path.Combine(new DirectoryInfo(Application.StartupPath).Parent.FullName, string.Format("{0}.lnk", "XChipTool_ISP3.0"))}"))
                    {
                        ShortCutHelper.Createashortcutontheparentpath("XChipTool_ISP3.0", Application.ExecutablePath, "mipiout");
                    }
                    if (!ShortCutHelper.DoesShortcutExist($"{Path.Combine(desktopPath, string.Format("{0}.lnk", "XChipTool_ISP3.0"))}"))
                    {
                        ShortCutHelper.CreateShortcutOnDesktop("XChipTool_ISP3.0", Application.ExecutablePath, "mipiout");
                    }
                    else
                    {
                        //获取桌面图标完整路径
                        string shortcutPath = Path.Combine(desktopPath, "XChipTool_ISP3.0.lnk");
                        //判断桌面图标快捷方式的目标路径
                        string targetPath = ShortCutHelper.GetShortcutTargetPath(shortcutPath);
                        //判断桌面图标快捷方式的目标路径文件是否存在
                        if (!File.Exists(targetPath))
                        {
                            // 删除快捷方式文件
                            File.Delete(shortcutPath);
                            ShortCutHelper.CreateShortcutOnDesktop("XChipTool_ISP3.0", Application.ExecutablePath, "mipiout");
                        }
                    }

                    if (ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["1ico"].Value == "0")
                    {
                        //获取桌面图标完整路径
                        string shortcutPath = Path.Combine(desktopPath, "XChipTool_ISP3.0.lnk");
                        //判断桌面图标快捷方式的目标路径
                        string targetPath = ShortCutHelper.GetShortcutTargetPath(shortcutPath);
                        //判断桌面图标快捷方式的目标路径文件是否存在
                        if (File.Exists(shortcutPath))
                        {
                            // 删除快捷方式文件
                            File.Delete(shortcutPath);
                            ShortCutHelper.CreateShortcutOnDesktop("XChipTool_ISP3.0", Application.ExecutablePath, "mipiout");
                            AppHelper.UpdateAppConfig("1ico", "1");
                        }
                    }
                }
                else
                {
                    if (!ShortCutHelper.DoesShortcutExist($"{Path.Combine(new DirectoryInfo(Application.StartupPath).Parent.FullName, string.Format("{0}.lnk", "XChipTool_Tve_ISP3.0"))}"))
                    {
                        ShortCutHelper.Createashortcutontheparentpath("XChipTool_Tve_ISP3.0", Application.ExecutablePath, "TVE");
                    }
                    if (!ShortCutHelper.DoesShortcutExist($"{Path.Combine(desktopPath, string.Format("{0}.lnk", "XChipTool_Tve_ISP3.0"))}"))
                    {
                        ShortCutHelper.CreateShortcutOnDesktop("XChipTool_Tve_ISP3.0", Application.ExecutablePath, "TVE");
                    }
                    else
                    {
                        //获取桌面图标完整路径
                        string shortcutPath = Path.Combine(desktopPath, "XChipTool_Tve_ISP3.0.lnk");
                        //判断桌面图标快捷方式的目标路径
                        string targetPath = ShortCutHelper.GetShortcutTargetPath(shortcutPath);
                        //判断桌面图标快捷方式的目标路径文件是否存在
                        if (!File.Exists(targetPath))
                        {
                            // 删除快捷方式文件
                            File.Delete(shortcutPath);
                            ShortCutHelper.CreateShortcutOnDesktop("XChipTool_Tve_ISP3.0", Application.ExecutablePath, "TVE");
                        }
                    }

                    if (ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["1ico"].Value == "0")
                    {
                        //获取桌面图标完整路径
                        string shortcutPath = Path.Combine(desktopPath, "XChipTool_Tve_ISP3.0.lnk");
                        //判断桌面图标快捷方式的目标路径
                        string targetPath = ShortCutHelper.GetShortcutTargetPath(shortcutPath);
                        //判断桌面图标快捷方式的目标路径文件是否存在
                        if (File.Exists(shortcutPath))
                        {
                            // 删除快捷方式文件
                            File.Delete(shortcutPath);
                            ShortCutHelper.CreateShortcutOnDesktop("XChipTool_Tve_ISP3.0", Application.ExecutablePath, "TVE");
                            AppHelper.UpdateAppConfig("1ico", "1");
                        }
                    }
                }
                

            }
            /**
            * 当前用户是管理员的时候，直接启动应用程序
            * 如果不是管理员，则使用启动对象启动程序，以确保使用管理员身份运行
            */
            //获得当前登录的Windows用户标示
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            //DateTime currentDate = DateTime.Now;
            //DateTime targetDate = new DateTime(2025, 1, 12);

            //if (currentDate.AddMonths(6) >= targetDate && currentDate.AddMonths(-6) <= targetDate)
            //{
            //    // 相差6个月或更短
            //}
            //else
            //{
            //    DevExpress.XtraEditors.XtraMessageBox.Show("版本已到期");
            //    return;
            //}

            //判断授权是否到期
            long lUsageDay = Convert.ToInt32(AppHelper.GetAppConfig("UsageDay"));
            if (lUsageDay > 0)
            {
                string strStartDay = AppHelper.GetAppConfig("StartDay");
                string strLastExitTime = AppHelper.GetAppConfig("LastExitTime");
                DateTime startDateTime;
                if (string.IsNullOrEmpty(strStartDay))
                {
                    startDateTime = DateTime.Now.ToLocalTime().Date;
                    AppHelper.UpdateAppConfig("StartDay", startDateTime.ToString());
                }
                else
                {
                    startDateTime = DateTime.Parse(strStartDay).Date;
                }
                DateTime curDateTime = DateTime.Now.ToLocalTime();
                if (!string.IsNullOrEmpty(strLastExitTime))
                {
                    DateTime lastDateTime = DateTime.Parse(strLastExitTime);
                    if (lastDateTime >= curDateTime)
                    {
                        MessageBox.Show("时间错误，与上次使用时间不相符，请确认时间!");
                        return;
                    }
                }
                if (lUsageDay < (curDateTime.Date - startDateTime).TotalDays)
                {
                    MessageBox.Show("使用时间已到期，请咨询本公司FAE部门延长使用时间!");
                    return;
                }
            }

            //判断当前登录用户是否为管理员
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                if (IntPtr.Size == 8)
                {
                    var dllPath = $"{System.Windows.Forms.Application.StartupPath}\\x64\\ver6.dll";
                    File.Copy(dllPath, $"{System.Windows.Forms.Application.StartupPath}\\ver6.dll", true);
                }
                else
                {
                    var dllPath = $"{System.Windows.Forms.Application.StartupPath}\\x86\\ver6.dll";
                    File.Copy(dllPath, $"{System.Windows.Forms.Application.StartupPath}\\ver6.dll", true);

                }
                if (GetConfigValue("ismipiout") != "1")
                {
                    if (GetConfigValue("IsSerial") == "TVE")
                    {
                        AutoUpdatorHelper.Start("http://49.232.124.138/xchiptool-isp3/tve/New/auto.xml", true);
                    }
                    else
                    {
                        if (GetConfigValue("IsI2C") == "1")
                        {
                            AutoUpdatorHelper.Start("http://49.232.124.138/xchiptool-isp3/i2c/New/auto.xml", true);
                        }
                        else
                        {
                            AutoUpdatorHelper.Start("http://49.232.124.138/xchiptool-isp3/usb/New/auto.xml", true);
                        }
                    }
                }
                


                if (ConfigurationManager.AppSettings["xcEdition"] == "0")
                {
                    //如果是管理员，则直接运行
                    Application.Run(new XChipForm());
                }
                else
                {
                    //如果是管理员，则直接运行
                    Application.Run(new XChip_Lite_Form());
                }

            }
            else
            {
                //创建启动对象
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.UseShellExecute = true;
                startInfo.WorkingDirectory = Environment.CurrentDirectory;
                startInfo.FileName = Application.ExecutablePath;
                //设置启动动作,确保以管理员身份运行
                startInfo.Verb = "runas";
                try
                {
                   
                    System.Diagnostics.Process.Start(startInfo);
                }
                catch
                {
                    return;
                }
                //退出
                Application.Exit();
            }
            AppHelper.UpdateAppConfig("LastExitTime", DateTime.Now.ToLocalTime().ToString());

        }
        private static string GetConfigValue(string strKey)
        {
            var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var settings = configFile.AppSettings.Settings;

            return settings[strKey].Value;
        }
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            //throw new NotImplementedException();
            logger.Debug(e.ToString());
        }

        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            logger.Debug(e.Exception.Message.ToString());
            //throw new NotImplementedException();
        }
    }
}
